//
//  MYGAnswerDetailHeaderView.swift
//  MYDoctor
//
//  Created by 小火科技 on 2024/5/29.
//

import UIKit
import QMUIKit

class MYGAnswerDetailHeaderView: UIView {
    
    var contentInset: UIEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 0, right: 15)
    var itemSpacing = 7.5
    var lineSpacing = 7.5
    var itemPerRow = 3
    
    var headerHeightBlock:((_ height:CGFloat) ->Void)?
    // MARK: - Property
    var model: MYGCommunityAnswerDetailModel = MYGCommunityAnswerDetailModel() {
        didSet {
            questionLabel.text = model.title
            let sex = model.patient?.gender == 1 ? "男" : "女"
            userInfoLabel.text = "\(sex) \(model.patient?.name ?? "")"
            publishInfoLabel.text = "\(model.region)"
            headImageView.sd_setImage(with: URL(string: model.patient?.avatar ?? ""), placeholderImage: headPlaceholderImage)
            
            contentLabel.text = model.question_content
           
            let size = getStringSize(font: .regular(14), viewSize: CGSize(width: screenWidth - 57 , height: CGFLOAT_MAX), str: model.question_content)
            
            let rows = ceil(Double(model.img.count) / Double(itemPerRow))
            let H:CGFloat = (rows * itemWidth() + (rows == 0 ? 0 : (rows - 1) * lineSpacing) + contentInset.top + contentInset.bottom)
            collectionView.snp.updateConstraints { make in
                make.height.equalTo(H)
            }
            collectionView.reloadData()
            headerHeightBlock?(H + size.height)
        }
        
    }
    
    private func itemWidth() -> CGFloat {
        let contentMargin = Double(30)
        let containerMargin = contentInset.left + contentInset.right
        let totalItemSpacing = itemSpacing > 1 ? itemSpacing * (Double(itemPerRow) - 1.0) : 0
        let total = contentMargin + containerMargin + totalItemSpacing
        let width = (screenWidth - total) / Double(itemPerRow)
        return width
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        configUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI
    private func configUI() {
        addSubviews([
            questionIcon,
            questionLabel,
            contentLabel,
            collectionView,
            headImageView,
            userInfoLabel,
            publishInfoLabel,
            line,
            answerIconImageView,
            titleLabel
        ])
        
        questionIcon.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(20)
            make.size.equalTo(CGSize(width: 25, height: 25))
        }
        
        questionLabel.snp.makeConstraints { make in
            make.left.equalTo(questionIcon.snp.right).offset(8.5)
            make.centerY.equalTo(questionIcon)
            make.right.equalToSuperview().offset(-15)
            make.height.greaterThanOrEqualTo(22.5)
        }
        
        contentLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(27)
            make.top.equalTo(questionLabel.snp.bottom).offset(13.5)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(contentLabel.snp.bottom).offset(10)
            make.height.equalTo(0)
        }
        
        headImageView.snp.makeConstraints { make in
            make.top.equalTo(collectionView.snp.bottom).offset(10)
            make.left.equalTo(15)
            make.size.equalTo(CGSize(width: 25, height: 25))
        }
        
        userInfoLabel.snp.makeConstraints { make in
            make.left.equalTo(headImageView.snp.right).offset(8.5)
            make.centerY.equalTo(headImageView)
        }
        
        publishInfoLabel.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(headImageView)
        }
        
        line.snp.makeConstraints { make in
            make.top.equalTo(userInfoLabel.snp.bottom).offset(18)
            make.height.equalTo(0.5)
            make.left.right.equalToSuperview()
        }
        
        answerIconImageView.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 25, height: 25))
            make.left.equalTo(15)
            make.top.equalTo(line.snp.bottom).offset(15)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerY.equalTo(answerIconImageView)
            make.left.equalTo(answerIconImageView.snp.right).offset(8)
        }
        
    }
    
    // MARK: - Public funcs
    
    // MARK: - lazy load
    private lazy var questionIcon: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "Community/question_icon"))
        return imageV
    }()
    
    private lazy var questionLabel: UILabel = {
        let label = UILabel()
        label.font = .medium(16)
        label.textColor = .rgba(51, 51, 51)
        label.numberOfLines = 0
        return label
    }()
    
    private lazy var contentLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(14)
        label.textColor = .rgba(72, 68, 67, 1)
        label.numberOfLines = 0
        return label
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isScrollEnabled = false
        collectionView.register(cellWithClass: MYGImagesUploadViewImageCell.self)
        return collectionView
    }()
    
    private lazy var headImageView: UIImageView = {
        let imageV = UIImageView(image: headPlaceholderImage)
        imageV.contentMode = .scaleAspectFill
        imageV.layerCornerRadius = 12.5
        return imageV
    }()
    
    private lazy var userInfoLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(13)
        label.textColor = .rgba(93, 93, 93)
        return label
    }()
    
    private lazy var publishInfoLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(13)
        label.textColor = .rgba(93, 93, 93)
        label.text = "2222"
        return label
    }()
    
    private lazy var line:UIView = {
        let line = UIView()
        line.backgroundColor = .rgba(238, 238, 238, 1)
        return line
    }()
    
    private lazy var answerIconImageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "Community/answer_icon"))
        return imageView
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "医生回答"
        label.textColor = .rgba(51, 51, 51)
        label.font = .medium(16)
        return label
    }()
    
        
}


extension MYGAnswerDetailHeaderView: QMUIImagePreviewViewDelegate {
    func numberOfImages(in imagePreviewView: QMUIImagePreviewView!) -> UInt {
        return UInt(model.img.count)
    }
    
    func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView!, renderZoomImageView zoomImageView: QMUIZoomImageView!, at index: UInt) {
        guard let cell = collectionView.cellForItem(at: IndexPath(item: Int(index), section: 0)) as? MYGImagesUploadViewImageCell else { return }
        zoomImageView.image = cell.imageView.image
    }
}


extension MYGAnswerDetailHeaderView: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return model.img.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: MYGImagesUploadViewImageCell.self, for: indexPath)
        let urlString =  model.img[indexPath.row]
        cell.imageView.sd_setImage(with: URL(string: urlString))
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let cell = collectionView.cellForItem(at: indexPath) as? MYGImagesUploadViewImageCell else { return }
        let vc = QMUIImagePreviewViewController()
        vc.imagePreviewView.delegate = self
        vc.imagePreviewView.currentImageIndex = UInt(indexPath.row)
        vc.sourceImageView = {
            return cell.imageView
        }
        vc.presentingStyle = .zoom
        vc.dismissingStyle = .fade
        UIViewController.currentViewController?.present(vc, animated: true)
    }
    
}
extension MYGAnswerDetailHeaderView: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
        CGSize(width: itemWidth(), height: itemWidth())
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        lineSpacing
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        itemSpacing
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        contentInset
    }
}
